#include <iostream>
#include <unordered_map>
#include <string>
#include "log.hpp"
#include <fstream>
#include<functional>

namespace dict_ns
{
    const std::string sep = ": ";
    const std::string defaultpath = "./Dict.txt";
    class Dict
    {
    private:
        bool Loading() // 将磁盘中内容装入内存中
        {
            std::ifstream in(_dict_conf_filepath); // 打开文件
            if (!in.is_open())
            {
                LOG(FATAL, "open %s error\n", _dict_conf_filepath);
                return false;
            }
            std::string line;
            while (std::getline(in, line)) // 从文件in中读取一行到line中
            {
                if (line.empty())
                    continue;              // 当读到空行是，继续读
                auto pos = line.find(sep); // 获取sep符号位置
                if (pos == std::string::npos)
                    continue;
                std::string word = line.substr(0, pos); // 获取一行中单词
                if (word.empty())
                    continue; // 当单词为空时继续
                std::string han = line.substr(pos + sep.size());
                if (han.empty())
                    continue;
                LOG(DEBUG, " load info: %s: %s\n", word.c_str(), han.c_str());
                _dict.insert(make_pair(word, han));
            }
            in.close();
            LOG(DEBUG, "load %s success \n", _dict_conf_filepath.c_str());
            return true;
        }

    public:
        Dict(const std::string path = defaultpath)
            : _dict_conf_filepath(path)
        {
            Loading();
        }
        std::string Translate(const std::string& word,bool & ok)
        {
            ok = true;
            auto iter = _dict.find(word);//在单词表职工查找单词
            if(iter == _dict.end())
            {
                ok = false;
                return "未找到";
            }
            return iter->second;
        }
        ~Dict()
        {
        }

    private:
        std::unordered_map<std::string, std::string> _dict;
        std::string _dict_conf_filepath;
    };
}